// 图像处理工具 - JavaScript核心逻辑
class ImageProcessor {
    constructor() {
        this.originalImage = null;
        this.canvas = document.getElementById('result-canvas');
        this.ctx = this.canvas.getContext('2d');
        this.processBtn = document.getElementById('process-btn');
        this.downloadBtn = document.getElementById('download-btn');
        
        // 初始化事件监听器
        this.initEventListeners();
        // 初始化颜色预览
        this.updateColorPreview();
    }

    initEventListeners() {
        // 文件上传相关
        const fileInput = document.getElementById('file-input');
        const uploadArea = document.getElementById('upload-area');

        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', () => fileInput.click());

        // 文件选择处理
        fileInput.addEventListener('change', (e) => this.handleFileSelect(e));

        // 拖拽上传处理
        uploadArea.addEventListener('dragover', (e) => this.handleDragOver(e));
        uploadArea.addEventListener('dragleave', (e) => this.handleDragLeave(e));
        uploadArea.addEventListener('drop', (e) => this.handleDrop(e));

        // 背景设置相关
        document.getElementById('bg-color-picker').addEventListener('change', (e) => {
            document.getElementById('bg-color-hex').value = e.target.value;
            this.updateColorPreview();
        });

        document.getElementById('bg-color-hex').addEventListener('input', (e) => {
            const color = e.target.value;
            if (/^#[0-9A-F]{6}$/i.test(color)) {
                document.getElementById('bg-color-picker').value = color;
                this.updateColorPreview();
            }
        });

        // 背景类型切换
        document.querySelectorAll('input[name="background"]').forEach(radio => {
            radio.addEventListener('change', () => this.updateColorPreview());
        });

        // 尺寸输入处理
        document.getElementById('width').addEventListener('input', () => this.updateTargetSize());
        document.getElementById('height').addEventListener('input', () => this.updateTargetSize());
    }

    // 处理文件选择
    handleFileSelect(event) {
        const file = event.target.files[0];
        if (file) {
            this.loadImage(file);
        }
    }

    // 处理拖拽悬停
    handleDragOver(event) {
        event.preventDefault();
        event.currentTarget.classList.add('dragover');
    }

    // 处理拖拽离开
    handleDragLeave(event) {
        event.currentTarget.classList.remove('dragover');
    }

    // 处理文件拖拽放下
    handleDrop(event) {
        event.preventDefault();
        event.currentTarget.classList.remove('dragover');
        
        const files = event.dataTransfer.files;
        if (files.length > 0) {
            const file = files[0];
            if (file.type.startsWith('image/')) {
                this.loadImage(file);
            } else {
                alert('请选择图片文件！');
            }
        }
    }

    // 加载图片
    loadImage(file) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
            alert('请选择有效的图片文件！');
            return;
        }

        // 验证文件大小 (10MB)
        if (file.size > 10 * 1024 * 1024) {
            alert('文件大小不能超过10MB！');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                this.originalImage = img;
                this.displayOriginalImage(img);
                this.updateImageInfo(file, img);
                this.processBtn.disabled = false;
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    // 显示原图预览
    displayOriginalImage(img) {
        const originalPreview = document.getElementById('original-preview');
        originalPreview.innerHTML = '';
        
        // 创建预览图片
        const previewImg = document.createElement('img');
        previewImg.src = img.src;
        previewImg.style.maxWidth = '100%';
        previewImg.style.maxHeight = '200px';
        previewImg.style.objectFit = 'contain';
        previewImg.className = 'rounded';
        
        originalPreview.appendChild(previewImg);
    }

    // 更新图片信息显示
    updateImageInfo(file, img) {
        document.getElementById('original-size').textContent = `${img.width} × ${img.height}`;
        document.getElementById('file-size').textContent = this.formatFileSize(file.size);
        document.getElementById('file-format').textContent = file.type.split('/')[1].toUpperCase();
        document.getElementById('image-info').style.display = 'block';
        this.updateTargetSize();
    }

    // 更新目标尺寸显示
    updateTargetSize() {
        const width = document.getElementById('width').value;
        const height = document.getElementById('height').value;
        document.getElementById('target-size').textContent = `${width} × ${height}`;
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 更新颜色预览
    updateColorPreview() {
        const preview = document.getElementById('color-preview');
        const isTransparent = document.getElementById('bg-transparent').checked;
        
        if (isTransparent) {
            preview.style.background = '';
            preview.classList.add('color-preview');
        } else {
            const color = document.getElementById('bg-color-picker').value;
            preview.style.background = color;
            preview.classList.remove('color-preview');
        }
    }

    // 处理图片 - 核心功能
    processImage() {
        if (!this.originalImage) {
            alert('请先上传图片！');
            return;
        }

        const width = parseInt(document.getElementById('width').value);
        const height = parseInt(document.getElementById('height').value);

        if (width <= 0 || height <= 0) {
            alert('请输入有效的尺寸！');
            return;
        }

        // 设置画布尺寸
        this.canvas.width = width;
        this.canvas.height = height;

        // 清空画布
        this.ctx.clearRect(0, 0, width, height);

        // 设置背景
        this.setBackground(width, height);

        // 绘制图片（居中）
        this.drawCenteredImage(width, height);

        // 显示结果
        this.showResult();
    }

    // 设置背景
    setBackground(width, height) {
        const isTransparent = document.getElementById('bg-transparent').checked;
        
        if (!isTransparent) {
            const color = document.getElementById('bg-color-picker').value;
            this.ctx.fillStyle = color;
            this.ctx.fillRect(0, 0, width, height);
        }
        // 透明背景不需要特殊处理，canvas默认就是透明的
    }

    // 绘制居中图片
    drawCenteredImage(canvasWidth, canvasHeight) {
        const img = this.originalImage;
        const imgWidth = img.width;
        const imgHeight = img.height;

        // 获取用户选择的缩放模式
        const scaleMode = document.querySelector('input[name="scale-mode"]:checked').value;
        
        let scale;
        if (scaleMode === 'original') {
            // 保持原尺寸
            scale = 1;
        } else {
            // 自适应缩放 - 计算缩放比例，保持图片宽高比
            const scaleX = canvasWidth / imgWidth;
            const scaleY = canvasHeight / imgHeight;
            scale = Math.min(scaleX, scaleY); // 使用较小的缩放比例，确保图片完全显示
        }

        // 计算缩放后的尺寸
        const scaledWidth = imgWidth * scale;
        const scaledHeight = imgHeight * scale;

        // 计算居中位置
        const x = (canvasWidth - scaledWidth) / 2;
        const y = (canvasHeight - scaledHeight) / 2;

        // 绘制图片
        this.ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
    }

    // 显示处理结果
    showResult() {
        document.getElementById('result-placeholder').style.display = 'none';
        this.canvas.style.display = 'block';
        this.downloadBtn.disabled = false;

        // 添加到预览容器的样式调整
        const container = this.canvas.parentElement;
        container.style.display = 'flex';
        container.style.justifyContent = 'center';
        container.style.alignItems = 'center';
    }

    // 下载图片
    downloadImage() {
        if (!this.canvas.width || !this.canvas.height) {
            alert('请先处理图片！');
            return;
        }

        // 创建下载链接
        const link = document.createElement('a');
        link.download = `processed_image_${Date.now()}.png`;
        link.href = this.canvas.toDataURL('image/png');
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// 全局函数（供HTML调用）
let imageProcessor;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    imageProcessor = new ImageProcessor();
});

// 设置预设尺寸
function setSize(width, height) {
    document.getElementById('width').value = width;
    document.getElementById('height').value = height;
    imageProcessor.updateTargetSize();
}

// 处理图片
function processImage() {
    imageProcessor.processImage();
}

// 下载图片
function downloadImage() {
    imageProcessor.downloadImage();
}